package com.lcp.se.service;

import com.lcp.se.entity.data.Appointment;
import com.lcp.se.entity.result.Message;
import com.lcp.se.entity.result.PageResultForMini;
import com.lcp.se.entity.result.Result;
import com.lcp.se.entity.vo.AppointmentVO;
import com.lcp.se.mapper.AppointmentMapper;
import com.lcp.se.util.MessageProperty;
import com.lcp.se.util.StatusCode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author lcp
 * @date 2020/7/26 20:27
 */
@Service
public class AppointmentService {
    @Resource
    private AppointmentMapper appointmentMapper;

    @Resource
    private AmqpMessageService amqpMessageService;

    /**
     * 创建预约
     *
     * @param appointmentVO 预约消息内容
     * @return 创建结果
     */
    public Result<Object> create(AppointmentVO appointmentVO, Appointment appointment) {
        if (appointmentVO == null || appointment == null) {
            return new Result<>(false, StatusCode.ERROR, "消息内容不能为空");
        }

        AppointmentVO result = appointmentMapper.unCompleted(appointment.getFromUserOpenId());
        if (result != null) {
            return Result.failure("预约创建失败");
        }

        // 可以用 socket 实时推送，也可以不推

        // 存入数据库
        return appointmentMapper.insert(appointment) == 1 ? Result.success("预约创建成功") : Result.failure("预约创建失败");
    }

    /**
     * 服务大厅列表
     *
     * @param pageSize    一页的大小
     * @param currentPage 当前页
     * @return 分页数据
     */
    public Result<PageResultForMini<AppointmentVO>> detailList(Integer pageSize, Integer currentPage) {
        currentPage = currentPage == null ? 1 : currentPage;
        List<AppointmentVO> resultList = appointmentMapper.detailList((currentPage - 1) * pageSize, pageSize, 0);
        Integer count = appointmentMapper.count(0);
        PageResultForMini<AppointmentVO> pageResult = new PageResultForMini<>(resultList, pageSize, currentPage, count);
        return new Result<>(true, StatusCode.OK, "查询成功", pageResult);
    }

    /**
     * 志愿者接受某一预约
     *
     * @param appointmentId    预约id
     * @param handleUserOpenId 志愿者id
     */
    public Result<Object> handle(String appointmentId, String handleUserOpenId) {
        // 检查是否有正在进行的预约，虽然小程序端有限制，但这里还是要以防万一
        if (appointmentMapper.selectProcessingAppointment(1, handleUserOpenId) != null) {
            return new Result<>(false, StatusCode.ERROR, "您还有正在进行的预约", null);
        }
        Appointment appointment = appointmentMapper.selectById(appointmentId);
        if (appointment.getMsgStatus() == 0) {
            int i = appointmentMapper.updateById(
                    new Appointment()
                            .setId(appointmentId)
                            .setMsgStatus(1)
                            .setHandleUserOpenId(handleUserOpenId)
                            .setHandleTime(new Date()));
            if (i == 1) {
                amqpMessageService.sendMessage(new Message<>(MessageProperty.MSG_APPOINTMENT_ACCEPTED, appointment.getFromUserOpenId()),
                        appointment.getFromUserOpenId());
                return new Result<>(true, StatusCode.OK, "接受预约成功");
            }
        }
        return new Result<>(false, StatusCode.ERROR, "操作失败，该预约已被其它人接受");
    }

    /**
     * 查询已接受未处理完（正在进行中）的预约（服务端）
     *
     * @param openId 志愿者id
     * @return 查询结果
     */
    public Result<AppointmentVO> processingAppointment(Integer userType, String openId) {
        AppointmentVO result = appointmentMapper.selectProcessingAppointment(userType, openId);
        if (result != null) {
            return new Result<>(true, StatusCode.OK, "查询成功", result);
        } else {
            return new Result<>(false, StatusCode.ERROR, "查询成功，没有正在进行的预约", null);
        }
    }

    /**
     * 取消/结束/完成预约
     */
    public Result<Object> complete(String appointmentId, Integer msgStatus) {
        return appointmentMapper.updateById(
                new Appointment()
                        .setId(appointmentId)
                        .setMsgStatus(msgStatus)
                        .setEndTime(new Date())) == 1 ? Result.success() : Result.failure();
    }

    /**
     * 查询求助者的未完成预约（不管是否被接受）,也就是状态码为0或1的预约
     *
     * @param openId 用户id
     * @return 查询结果
     */
    public Result<AppointmentVO> unCompleted(String openId) {
        AppointmentVO result = appointmentMapper.unCompleted(openId);
        if (result != null) {
            return new Result<>(true, StatusCode.OK, "查询成功", result);
        } else {
            return new Result<>(false, StatusCode.ERROR, "查询成功，可以发起新的预约", null);
        }
    }
}